from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.decorators import action
from rest_framework.exceptions import APIException

from django.core.cache import cache

from utils.common import add  # pycharm提示爆红，但是没有错
from utils.log import logger
from utils.response import APIResponse
from .serializer import MulLoginSerializer,SmsLoginSerializer,RegisterSerializer
from .models import User
from libs import tencent_sms_v3
from utils.pool import POOL
import redis
# from django_redis import get_redis_connection
from django.core.cache import cache
# from django.core import cache
# class TestView(APIView):
#     def get(self, requeste):
#         # conn=redis.Redis(connection_pool=POOL)
#         # print(conn.get('name'))
#         # conn=get_redis_connection()
#         # print(conn.get('name'))
#         cache.set('wife',['dlrb','lyf']) # django的缓存，放在redis中
#         # print(cache.get('name'))
#         res = add(8, 9)
#         # 记录日志
#         logger.info("我执行了一下")
#         print(res)
#         return Response('ok')
from celery_task.user_task import create_user
class TestView(APIView):
    def get(self, request):
        # create_user.delay('12222222','lqznb','lqz12345')
        ip=request.META.get('REMOTE_ADDR')
        return Response('小伙子您的ip是：%s'%ip)


class MobileView(ViewSet):
    # get 请求携带手机号，就能校验手机号
    @action(methods=["GET"], detail=False)
    def check_mobile(self, request):
        try:
            mobile = request.query_params.get('mobile')
            User.objects.get(mobile=mobile)
            return APIResponse()  # {code:100,msg:成功}-->前端判断，100就是手机号存在，非100，手机号步骤
        except Exception as e:
            raise APIException(str(e))  # 处理了全局异常，这里没问题

class LoginView(GenericViewSet):
    serializer_class = MulLoginSerializer
    queryset = User

    # 两个登陆方式都写在这里面（多方式，一个是验证码登陆）
    # login不是保存，但是用post，咱们的想法是把验证逻辑写到序列化类中
    @action(methods=["post"], detail=False)
    def mul_login(self, request):
        return self._common_login(request)


    # 127.0.0.1:8000/api/v1/user/login/sms_login
    @action(methods=["post"], detail=False)
    def sms_login(self, request):
        # 默认情况下使用的序列化类使用的是MulLoginSerializer---》多方式登陆的逻辑-->不符合短信登陆逻辑
        # 再新写一个序列化类，给短信登陆用
        return self._common_login(request)
    def get_serializer_class(self):
        # 方式一：
        # if 'mul_login' in self.request.path:
        #     return self.serializer_class
        # else:
        #     return SmsLoginSerializer
        # 方式二
        if self.action=='mul_login':
            return self.serializer_class
        else:
            return SmsLoginSerializer


    def _common_login(self,request):
        try:
            # 序列化类在变
            ser = self.get_serializer(data=request.data, context={'request': request})
            ser.is_valid(raise_exception=True)  # 如果校验失败，直接抛异常，不需要加if判断了
            token = ser.context.get('token')
            username = ser.context.get('username')
            icon = ser.context.get('icon')
            return APIResponse(token=token, username=username, icon=icon)  # {code:100,msg:成功，token:dsadsf,username:lqz}
        except Exception as e:
            raise APIException(str(e))

class SendSmsView(ViewSet):
    @action(methods=['GET'], detail=False)
    def send_message(self, request):
        try:
            phone = request.query_params.get('phone')
            # 生成验证码
            code = tencent_sms_v3.get_code()
            print(code)
            # code要保存，否则后面没法验证
            # sms_cache_%s格式化的字符串可以放到配置文件中---》用户自定义配置
            cache.set('sms_cache_%s'%phone,code,60) # 设置值，key value形式，key应该唯一，使用手机号
            # cache.get() # 取值，根据key取

            # 同步操作---》后期可以使用异步操作---》开一个线程调用
            res = tencent_sms_v3.send_sms(phone, code)
            if res:
                return APIResponse(msg='短信发送成功')
            else:
                raise APIException("短信发送失败")
        except Exception as e:
            raise APIException(str(e))


# 自动生成路由，新增数据create，post
from rest_framework.mixins import CreateModelMixin
class RegisterView(GenericViewSet,CreateModelMixin):
    serializer_class = RegisterSerializer
    queryset = User.objects.all()
    def create(self, request, *args, **kwargs):
        # 方式一：
        super().create(request, *args, **kwargs)  # 小问题,code不是表的字段，需要用write_only

        # 方式二：
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # # self.perform_create(serializer)
        # serializer.save()

        return APIResponse(msg='注册成功')



